package com.office.personalOffice.personalInfo.service.impl;

/**
 * @author shkstart
 * @create 2022-11-07 9:32
 */

import com.office.personalOffice.personalInfo.dao.IPersonalInfo;
import com.office.personalOffice.personalInfo.model.LoginUser;
import com.office.personalOffice.personalInfo.model.ResponseResult;
import com.office.personalOffice.personalInfo.model.TbStaff;
import com.office.personalOffice.personalInfo.service.LoginServcie;
import com.office.util.JwtUtil;
import com.office.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginServcie, UserDetailsService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IPersonalInfo userMapper;


    @Override
    public ResponseResult logout(LoginUser loginUser) {
        Integer id = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + id);
        SecurityContextHolder.clearContext();
        return new ResponseResult(200, "退出成功");
    }

    @Override
    public ResponseResult login(TbStaff user) {
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //根据用户名查询用户信息
        TbStaff login = userMapper.login(username);
        Object cacheObject = redisCache.getCacheObject("login:" + login.getId().toString());

        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(login)) {
            return new LoginUser(null);
        }
        //使用userid生成token
        String userId = login.getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:" + userId, jwt);
        //TODO 根据用户查询权限信息 添加到LoginUser中

        //封装成UserDetails对象返回
        return new LoginUser(login);
    }
}

